var CompanyMaterialForm = function () {
  var companyArr = ['铂亮光学']; //"铂亮光学"

  var template = /* html */ `
    <div class="companyMaterialForm" v-loading.fullscreen.lock="loading">
      <el-form class="material-form" label-width="120px">
        <template v-if="type==='update'">
          <el-form-item label="物料代码">
            <el-input class="form-input" v-if="type!=='update'" v-model="companyMaterial.materialCode"></el-input>
            <span v-else>{{companyMaterial.materialCode}}</span>
          </el-form-item>
        </template>
        <el-form-item label="物料名称" required>
          <el-autocomplete v-if="selectStatus" class="form-input" :disabled="isNotChange()" v-model="companyMaterial.materialName"
            :fetch-suggestions="function(){getSuggestionData('materialNameList',arguments)}">
          </el-autocomplete>
          <span v-else>{{companyMaterial.materialName}}</span>
        </el-form-item>
        <el-form-item label="物料图片" v-if="(type==='update' && companyMaterial.id!=='') || type==='add'">
          <imgs-upload :img-width="178" :img-height="178" ref="materialImgsUpload" v-model="companyMaterial.imgUrls" :limit="4" :auto-upload="false"></imgs-upload>
        </el-form-item>
        <el-form-item label="规格" required>
          <el-autocomplete class="form-input" v-if="selectStatus" v-model="companyMaterial.model"
            :fetch-suggestions="function(){getSuggestionData('modelList',arguments)}">
          </el-autocomplete>
          <span v-else>{{companyMaterial.model}}</span>
        </el-form-item>
        <el-form-item label="编号">
          <el-autocomplete class="form-input" v-if="selectStatus" v-model="companyMaterial.color"
            :fetch-suggestions="function(){getSuggestionData('colorList',arguments)}">
          </el-autocomplete>
          <span v-else>{{companyMaterial.color}}</span>
        </el-form-item>
        <el-form-item label="描述">
          <el-input class="form-input" v-if="selectStatus||isUpdateColorDesc" v-model="companyMaterial.colorDescription"></el-input>
          <span v-else>{{companyMaterial.colorDescription}}</span>
        </el-form-item>
        <el-form-item label="物料部门">
          <el-select clearable filterable v-if="selectStatus" class="form-input" v-model="companyMaterial.materialDept" value-key="materialDeptId">
            <el-option v-for="dept in deptList" :key="dept.materialDeptId" :value="dept" :label="dept.materialDeptName">
            </el-option>
          </el-select>
          <span v-else>{{companyMaterial.materialDept!==''?companyMaterial.materialDept.materialDeptName:''}}</span>
        </el-form-item>
        <el-form-item label="材质">
          <el-input class="form-input" v-model="companyMaterial.material"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select class="form-input" v-model="companyMaterial.status" placeholder="请选择">
            <el-option label="使用" value="使用"></el-option>
            <el-option label="禁用" value="禁用"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="默认仓库">
          <el-select class="form-input" v-if="selectStatus" v-model="companyMaterial.defaultWarehouse" @change="changeDefaultWarehouse">
            <el-option label="原材料仓" value="原材料仓"></el-option>
            <el-option label="辅料仓" value="辅料仓"></el-option>
          </el-select>
          <span v-else>{{companyMaterial.defaultWarehouse}}</span>
        </el-form-item>
        <el-form-item label="物料类型">
          <el-select clearable filterable class="form-input" @change="changeMaterialType" v-model="companyMaterial.materialType">
            <el-option v-for="materialType in materialTypeList" :key="materialType" :value="materialType">
            </el-option>
          </el-select>
        </el-form-item>
        <template v-if="companyMaterial.defaultWarehouse==='原材料仓' && companyMaterial.materialType==='镜片'">
          <el-form-item label="透光率">
            <el-input-number is-decimal-zero class="form-input" :min="0" :max="100" :controls="false" :precision="2" v-model="companyMaterial.transmittance"></el-input-number>
          </el-form-item>
        </template>
        <el-form-item label="供应商" required>
          <filter-select clearable v-if="selectStatus" :class="{'form-input':type!=='add'}" v-model="companyMaterial.providerName" :options="getDropdown('providerList')" value-field="name" label-field="name"
            :filter-method="providerFilterMehod">
            <template slot="item" slot-scope="scope">
              <div class="clearfix">
                <span>{{scope.option.name}}</span>
                <span style="float:right;color:#8492a6;margin-left:10px">{{scope.option.code}}</span>
              </div>
            </template>
          </filter-select>
          <span v-else>{{companyMaterial.providerName}}</span>
          <el-button type="primary" v-if="type==='add'&&isShowAddProviderName===1" @click="addProviderName">添加供应商</el-button>
        </el-form-item>
        <el-form-item label="供方编号">
          <el-input class="form-input" v-model="companyMaterial.providerNo"></el-input>
        </el-form-item>
        <el-form-item label="单位" required>
          <el-select class="form-input" v-if="selectStatus" v-model="companyMaterial.unit" filterable="true" @change="changeUnit" placeholder="请选择">
            <el-option v-for="unit in getDropdown('unitList')" :key="unit" :value="unit">
            </el-option>
          </el-select>
          <span v-else>{{companyMaterial.unit}}</span>
        </el-form-item>
        <el-form-item label="单价">
          <el-input-number is-decimal-zero class="form-input" :controls="false" v-model="companyMaterial.unitPrice" :min="0" :max="999999" :precision="4">
          </el-input-number>
        </el-form-item>
        <el-form-item class="input-item" label="计价单位与生产单位是否相同">
          <span>{{companyMaterial.isEquals===1?'相同':'不相同'}}</span>
        </el-form-item>
        <el-form-item label="采购周期">
          <el-input-number class="form-input" :controls="false" v-model="companyMaterial.procurementCycles" :min="0" :max="365" :precision="0">
          </el-input-number>
        </el-form-item>
        <el-form-item label="库存上限">
          <el-input-number class="form-input" :controls="false" v-model="companyMaterial.safetyStockMax" :min="0" :max="9999999999" :precision="2">
          </el-input-number>
        </el-form-item>
        <el-form-item label="库存下限">
          <el-input-number class="form-input" :controls="false" v-model="companyMaterial.safetyStockMin" :min="0" :max="9999999999" :precision="2">
          </el-input-number>
        </el-form-item>
        <template v-if="type==='update'">
          <el-form-item label="创建人">
            <span>{{companyMaterial.creater}}</span>
          </el-form-item>
        </template>
        <template v-if="type==='update'">
          <el-form-item label="创建时间">
            <span>{{companyMaterial.creationTime}}</span>
          </el-form-item>
        </template>
        <template v-if="type==='update'">
          <el-form-item label="最后修改人">
            <span>{{companyMaterial.lastModifier}}</span>
          </el-form-item>
        </template>
        <template v-if="type==='update'">
          <el-form-item label="最后修改时间">
            <span>{{companyMaterial.lastModifyTime}}</span>
          </el-form-item>
        </template>
        <el-form-item>
          <el-button type="primary" v-if="type==='update'" @click="saveCompanyMaterial">修改</el-button>
          <el-button type="primary" v-else-if="type==='add'" @click="saveCompanyMaterial">保存</el-button>
          <el-button type="primary" v-if="type==='update'&&companyMaterial.purchaseApproval!==1" @click="approvalCompanyMaterial">
            审核
          </el-button>
        </el-form-item>
      </el-form>
      <el-dialog title="添加供应商" append-to-body :close-on-press-escape="false" :close-on-click-modal="false" :visible.sync="isShowCustomerAddForm"
        top="5vh">
        <div style="height: calc(80vh - 54px); overflow: auto">
          <customer-form v-if="isShowCustomerAddForm" :customer-type="1" @save-success="addCustomerAfter">
          </customer-form>
        </div>
      </el-dialog>
    </div>
  `;
  return {
    props: {
      companyMaterial: {
        type: Object,
        required: true
      },
      type: {
        type: String,
        default: 'add'
      },
      dropdownOption: {
        type: Object,
        required: true
      },
      isShowAddProviderName: {
        type: Number,
        default: 1
      }
    },

    watch: {
      'companyMaterial.img': function () {
        var showImgUrl = this.companyMaterial.img;
        if (showImgUrl === undefined) {
          showImgUrl = '';
        }
        this.showImgUrl = showImgUrl;
      },
      companyMaterial: function () {
        this.loading = true;
        var self = this;
        this.setSelectStatus().then(function () {
          self.loading = false;
        });
      }
    },
    data: function () {
      var showImgUrl = this.companyMaterial.img;
      if (showImgUrl === undefined) {
        showImgUrl = '';
      }
      var user = window.sessionStorage.getItem("user");
      var isUpdateColorDesc = false;
      if (!SysUtil.isEmpty(user)) {
        user = JSON.parse(user);
        isUpdateColorDesc = companyArr.indexOf(user.company) !== -1;
      }
      return {
        loading: false,
        showImgUrl: showImgUrl,
        isUpdateColorDesc: isUpdateColorDesc,
        materialTypeList: [],
        selectStatus: false,
        isShowCustomerAddForm: false,
        deptList: []
      }
    },
    created: function () {
      var companyMaterial = this.companyMaterial;
      if (companyMaterial === undefined) {
        this.setMaterialTypeList(1, true);
      } else {
        if (companyMaterial.defaultWarehouse === '原材料仓') {
          this.setMaterialTypeList(1, true);
        } else {
          this.setMaterialTypeList(2, true);
        }
      }
      this.changeMaterialType();

      this.loading = true;
      var self = this;
      Promise.all([
        this.initDropdownData(),
        this.setSelectStatus()
      ]).then(function () {
        self.loading = false;
      });
    },
    methods: {
      initDropdownData: function () {
        var promiseObj = {
          materialNameList: this.setMaterialNameList,
          colorList: this.setColorList,
          modelList: this.setModelList,
          providerList: this.setProviderList,
          unitList: this.setUnitList
        };
        var promiseList = [this.setDeptList()];
        var dropdownOption = this.dropdownOption;
        for (var field in promiseObj) {
          if (dropdownOption[field] === undefined) {
            promiseList.push(promiseObj[field]());
          }
        }

        if (promiseList.length === 0) {
          return Promise.resolve();
        }

        return Promise.all(promiseList).then(function (res) {
          return res;
        }).catch(function () {
          return null;
        });
      },
      setSelectStatus: function () {
        if (this.type === 'add') {
          this.selectStatus = true;
          return Promise.resolve();
        }

        var materialCode = this.companyMaterial.materialCode;
        if (materialCode === '') {
          this.selectStatus = false;
          return Promise.resolve();
        }

        var self = this;
        return ajaxRequest('basicData/queryMaterialCompanyIsUsed', {
          materialCode: materialCode
        }).then(function (isUsed) {
          self.selectStatus = isUsed === 0;
          return isUsed;
        }).catch(function () {
          return false;
        });
      },
      // 获取物料名称
      setMaterialNameList: function () {
        var self = this;
        return ajaxRequest("basicData/getCompanyMaterialName").then(function (res) {
          self.dropdownOption.materialNameList = res;
          return res;
        });
      },
      // 获取规格
      setModelList: function () {
        var self = this;
        return ajaxRequest("basicData/getCompanyModel").then(function (res) {
          self.dropdownOption.modelList = res;
          return res;
        });
      },
      // 获取编号
      setColorList: function () {
        var self = this;
        return ajaxRequest("basicData/getCompanyColor").then(function (res) {
          self.dropdownOption.colorList = res;
          return res;
        });
      },
      // 获取供应商
      setProviderList: function () {
        var self = this;
        return ajaxRequest("basicData/getCustomerName", {
          view: 1
        }).then(function (res) {
          var providerList = [];
          for (var i = 0; i < res.length; i++) {
            var name = res[i].customerName.trim();
            var code = res[i].customerCode;
            providerList.push({
              name: name,
              code: code
            });
          }
          self.dropdownOption.providerList = providerList;
          return providerList;
        });
      },
      // 获取公共单位
      setUnitList: function () {
        var self = this;
        return ajaxRequest("basicData/getCompanyUnit").then(function (unitList) {
          unitList = _.orderBy(unitList, [function (value) {
            if (['条', '付'].indexOf(value) !== -1) {
              return 0;
            }
            return 1;
          }], ['asc']);
          self.dropdownOption.unitList = unitList;
          return unitList;
        });
      },
      setDeptList: function () {
        var deptList = this.dropdownOption.deptList;
        if (deptList !== undefined) {
          this.deptList = deptList;
          return Promise.resolve(deptList);
        }

        var self = this;
        return ajaxRequest('basicData/getDeptName', {
          view: 1
        }).then(function (deptList) {
          deptList = _.map(deptList, function (dept) {
            return {
              materialDeptId: dept.id,
              materialDeptName: dept.deptName
            };
          });
          self.deptList = deptList;
          self.dropdownOption.deptList = deptList;
          return deptList;
        });
      },
      // 过滤
      getSuggestionData: function (field, arr) {
        var queryString = arr[0];
        var cb = arr[1];
        var dropdownOption = this.dropdownOption;
        var suggestList = dropdownOption[field];
        if (suggestList === undefined) {
          return [];
        }

        if (queryString !== '') {
          suggestList = _.filter(suggestList, function (suggest) {
            return suggest.indexOf(queryString) !== -1;
          });
        }
        suggestList = _.map(suggestList, function (suggest) {
          return {
            value: suggest
          };
        });
        cb(suggestList);
      },
      // 修改物料
      saveCompanyMaterial: function () {
        var companyMaterial = this.companyMaterial;
        if (!companyMaterial.checkValid()) {
          return;
        }

        var self = this;
        this.$refs['materialImgsUpload'].submit().then(function () {
          var type = self.type;
          var postData = companyMaterial.getObject(type);
          if (type === 'add') {
            self.addCompanyMaterial(postData);
          } else {
            self.updateCompanyMaterial(postData);
          }
        });
      },
      updateCompanyMaterial: function (postData) {
        var self = this;
        self.loading = true;
        ajaxRequest("basicData/updateCompanyMaterial", postData).then(function (res) {
          self.$alert('操作成功', '信息');
          self.$emit('update');
          self.loading = false;
        }).catch(function () {
          self.loading = false;
        });
      },
      // 新增物料
      addCompanyMaterial: function (postData) {
        var self = this;
        self.loading = true;
        ajaxRequest("basicData/insertCompanyMaterial", postData).then(function (res) {
          self.$alert('操作成功', '信息');
          self.$emit('add', res[0]);
          self.loading = false;
        }).catch(function () {
          self.loading = false;
        });
      },
      approvalCompanyMaterial: function () {
        var companyMaterial = this.companyMaterial;
        if (!companyMaterial.checkValid()) {
          return;
        }

        var postData = companyMaterial.getObject('update');
        var self = this;
        self.loading = true;
        ajaxRequest("basicData/approvalCompanyMaterial", postData).then(function (res) {
          self.$alert('操作成功', '信息');
          self.$emit('update');
          self.loading = false;
        }).catch(function () {
          self.loading = false;
        });
      },
      // 修改默认仓库后
      changeDefaultWarehouse: function () {
        this.setMaterialTypeList();
      },
      // 改变单位时
      changeUnit: function () {
        var companyMaterial = this.companyMaterial;
        if (companyMaterial.unit === '付') {
          companyMaterial.isEquals = 1;
        } else {
          companyMaterial.isEquals = 0;
        }
      },
      changeMaterialType: function () {
        var companyMaterial = this.companyMaterial;
        var materialType = companyMaterial.materialType;
        if (companyMaterial.defaultWarehouse === '原材料仓') {
          if (materialType !== null && materialType.indexOf("板材") > -1) {
            companyMaterial.materialName = '胶板料';
          }
        }
      },
      isNotChange: function () {
        var companyMaterial = this.companyMaterial;
        var materialType = companyMaterial.materialType;
        if (companyMaterial.defaultWarehouse === '原材料仓') {
          if (materialType !== null && materialType.indexOf("板材") > -1) {
            return true;
          }
        }
        return false;
      },
      // 添加供应商
      addProviderName: function () {
        this.isShowCustomerAddForm = true;
      },
      // 添加完供应商后
      addCustomerAfter: function (customer) {
        this.isShowCustomerAddForm = false;
        this.loading = true;
        var self = this;
        this.setProviderList().then(function () {
          self.loading = false;
          self.companyMaterial.providerName = customer.customerName;
        }).catch(function () {
          self.loading = false;
        });
      },
      // 获取物料类型
      setMaterialTypeList: function (defaultWarehouse, notClean) {
        var self = this;
        var companyMaterial = this.companyMaterial;
        var postData = {};
        if (defaultWarehouse === undefined) {
          if (companyMaterial.defaultWarehouse === "原材料仓") {
            postData.defaultWarehouse = 1;
          } else if (companyMaterial.defaultWarehouse === "辅料仓") {
            postData.defaultWarehouse = 2;
          }
        } else {
          postData.defaultWarehouse = defaultWarehouse;
        }
        ajaxRequest("basicData/getRowMaterialType", postData).then(function (res) {
          self.materialTypeList = res;
          if (!notClean) {
            companyMaterial.materialType = "";
          }
        })
      },
      getDropdown: function (field) {
        var dropdownOption = this.dropdownOption;
        var list = dropdownOption[field];
        if (list === undefined) {
          return [];
        }
        return list;
      },
      providerFilterMehod:function(query, option){
        if (query === '') {
          return true;
        }
        query = query.toLowerCase();

        var code = option.code;
        code = code.toLowerCase();
        var name = option.name;
        name = name.toLowerCase();
        return code.indexOf(query) !== -1 || name.indexOf(query) !== -1;
      }
    },
    components: {
      CustomerForm: CustomerForm,
      ImgsUpload: ImgsUpload,
      FilterSelect: FilterSelect
    },
    template: template
  };
}();
